//
//  GoodsDetailViewController.m
//  Consume100
//
//  Created by eliot on 16/3/29.
//  Copyright © 2016年 aleven. All rights reserved.
//

#import "GoodsDetailViewController.h"

#import "GoodsDetailTableViewCell.h"

#import "SubmitDetialTableViewController.h"

#import "MJRefresh.h"

@interface GoodsDetailViewController ()<UITableViewDataSource, UITableViewDelegate, UIScrollViewDelegate>

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *BGVH;

@property (weak, nonatomic) IBOutlet UITableView *topTableVIew;

@property (weak, nonatomic) IBOutlet UILabel *exchangeLb;//

@property (weak, nonatomic) IBOutlet UILabel *priceLb;//

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *priceLbH;
@property (weak, nonatomic) IBOutlet UILabel *goldLb;//

@property (weak, nonatomic) IBOutlet UILabel *baoyouLb;//
@property (weak, nonatomic) IBOutlet UIButton *exchangeBtn;

@property (nonatomic, strong) UIScrollView *sc;

@property (nonatomic, assign) CGFloat contentOffsetY;
@property (nonatomic, assign) CGFloat oldContentOffsetY;


@property (nonatomic, strong) NSDictionary *dataDic;

@property (nonatomic, strong) NSDictionary *firstCellDic;
@end

@implementation GoodsDetailViewController

+(GoodsDetailViewController*)CreatGoodsDetailViewController{
    
    UIStoryboard *story=[UIStoryboard storyboardWithName:@"Main" bundle:nil];
    
    GoodsDetailViewController *GoodsDetailViewController=[story instantiateViewControllerWithIdentifier:@"GoodsDetailViewController"];
    
    return GoodsDetailViewController;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.exchangeLb.hidden = YES;
    self.priceLb.hidden = YES;
    self.goldLb.hidden = YES;
    self.baoyouLb.hidden = YES;

    
    self.exchangeBtn.layer.cornerRadius = 10;
    self.exchangeBtn.layer.masksToBounds = YES;
    self.exchangeBtn.backgroundColor = [UIColor colorWithRed:255/255.0 green:88/255.0 blue:88/255.0 alpha:1];
    UIFont *fnt = [UIFont systemFontOfSize:15];
    CGSize size = [self.priceLb.text sizeWithAttributes:[NSDictionary dictionaryWithObjectsAndKeys:fnt,NSFontAttributeName, nil]];
    CGFloat nameH = size.height;
    self.priceLbH.constant = nameH;
    self.title = @"商品详情";
    
    self.BGVH.constant = 55;
    self.priceLbH.constant = 100;
    self.priceLb.textAlignment = NSTextAlignmentCenter;
    self.topTableVIew.backgroundColor = [UIColor colorWithRed:237/255.0 green:237/255.0 blue:237/255.0 alpha:1];
    /** 设置导航啦样式*/
    [self.navigationController.navigationBar setTitleTextAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:19],NSForegroundColorAttributeName:[UIColor whiteColor]}];
    self.navigationController.navigationBar.tintColor = [UIColor whiteColor];
    [self.navigationController.navigationBar setTitleTextAttributes:@{NSForegroundColorAttributeName : [UIColor whiteColor]}];
    self.navigationController.navigationBar.translucent = NO;
    
    [self.topTableVIew registerNib:[UINib nibWithNibName:@"GoodsDetailTableViewCell" bundle:nil] forCellReuseIdentifier:@"GoodsDetailTableViewCell"];
    MJRefreshBackGifFooter *footer = [MJRefreshBackGifFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
    // 设置尾部/Users/eliot/Desktop/Consume100/Consume100
    self.topTableVIew.mj_footer = footer;
    
    
    self.topTableVIew.tableFooterView = [[UIView alloc] init];
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    manager.requestSerializer.timeoutInterval = 5;
    NSDictionary *dic = @{@"productId":self.productId};
    NSString *baseUrl = [NSString stringWithFormat:@"%@getShopProductById.jhtml", MyBaseURL];
    [manager POST:baseUrl parameters:dic progress:^(NSProgress * _Nonnull uploadProgress) {
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        NSArray *arr = dic[@"shopProductJson"];
        dispatch_async(dispatch_get_main_queue(), ^{
            self.dataDic = arr.firstObject;
            self.priceLb.text = [NSString stringWithFormat:@"%@", self.dataDic[@"price"]];
            self.firstCellDic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
            
            [self.topTableVIew reloadData];
        });
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [MBProgressHUD hideHUD];
            [MBProgressHUD showError:@"链接超时,请检查网络"];
        });
    }];
    
    
}

-(UIScrollView *)sc {
    if (!_sc) {
        _sc = [[UIScrollView alloc] init];
        [self.view addSubview:_sc];
        _sc.frame = CGRectMake(0, Height, Width, Height - 114);
        UIImageView *iv = [[UIImageView alloc] init];
        iv.contentMode = UIViewContentModeScaleAspectFit;
        iv.image = [UIImage imageNamed:@"图层 16"];
        [_sc  addSubview:iv];
        iv.frame = CGRectMake(0, 0, Width, 1997 / 750.0 * Width);
        _sc.delegate = self;
        [_sc setContentSize:CGSizeMake(Width,  1997 / 750.0 * Width)];
        self.sc.maximumZoomScale = 2.0;
    }
    return _sc;
}


/**  上拉*/
- (void)loadMoreData {
   
    [UIView animateWithDuration:0.5 animations:^{
        self.sc.frame = CGRectMake(0, 0, Width, Height - 114);
        self.topTableVIew.hidden = YES;
        self.exchangeBtn.transform = CGAffineTransformMakeTranslation(Width / 2.0 - self.exchangeBtn.frame.size.width / 2 - 10, 0);
        self.exchangeLb.hidden = NO;
        self.priceLb.hidden = NO;
        
        self.goldLb.hidden = NO;
        self.baoyouLb.hidden = NO;
    }];
    
    self.sc.indicatorStyle = UIScrollViewIndicatorStyleDefault;
    [self.topTableVIew.mj_footer endRefreshing];
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {
    
    self.oldContentOffsetY = scrollView.contentOffset.y;
    
   
}
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    
    
    
    self.contentOffsetY = scrollView.contentOffset.y;
    
    
    
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    [self.topTableVIew.mj_footer endRefreshing];
    CGFloat newContentOffsetY;

    newContentOffsetY = scrollView.contentOffset.y;
    
    if (newContentOffsetY > self.oldContentOffsetY && self.oldContentOffsetY > self.contentOffsetY) { //
        
        
        
    } else if (newContentOffsetY < self.oldContentOffsetY && self.oldContentOffsetY < self.contentOffsetY) {//向下滚动
        CGPoint point = scrollView.contentOffset;
        
      
        
        if (point.x == 0.0f && point.y <= -80) {
            [UIView animateWithDuration:0.5 animations:^{
                self.sc.frame = CGRectMake(0, Height, Width, Height - 114);
                self.topTableVIew.hidden = NO;
            }];
            
            
        }
        if (newContentOffsetY < -140) {
            
        }
        
        
    }
}




- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
}

#pragma mark - tableView (tableViewDelegate/tableViewDataSource)

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    if (tableView == self.topTableVIew) {
        return 2;
    }else {
        return 0;
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (tableView == self.topTableVIew) {
        if (section == 0) {
            return 1;
            
        }else {
            return 2;
        }
    }else {
        return 6;
    }

}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (tableView == self.topTableVIew) {
        if (indexPath.section == 0) {
            GoodsDetailTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"GoodsDetailTableViewCell" forIndexPath:indexPath];
            [cell setupCellWithDic:self.firstCellDic];
            return cell;
        }else {
            UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cellFirst"];
            if (!cell) {
                cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"cellFirst"];
            }
            if (indexPath.row == 0) {
                cell.textLabel.text = [NSString stringWithFormat:@"换购价格:%@金币", self.dataDic[@"price"]];
                cell.textLabel.textColor = [UIColor colorWithRed:82/255.0 green:82/255.0 blue:82/255.0 alpha:1];
                 cell.detailTextLabel.textColor = [UIColor colorWithRed:136/255.0 green:136/255.0 blue:136/255.0 alpha:1];
                NSMutableAttributedString *hintString=[[NSMutableAttributedString alloc]initWithString:cell.textLabel.text];
                //获取要调整颜色的文字位置,调整颜色
                NSRange range1=[[hintString string]rangeOfString:@"6588"];
                [hintString addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:range1];
                cell.textLabel.attributedText = hintString;
                cell.detailTextLabel.text = [NSString stringWithFormat:@"已换购%@份", self.dataDic[@"sales"]];
                return cell;
            }else {
                cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@"cellFirst"];
                cell.textLabel.text = @"上拉查看图文详情";
                cell.textLabel.textColor = [UIColor colorWithRed:82/255.0 green:82/255.0 blue:82/255.0 alpha:1];
                cell.textLabel.textAlignment = NSTextAlignmentCenter;
                return cell;
            }
        }
        
    }else {
        return nil;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (tableView == self.topTableVIew) {
        if (indexPath.section == 0) {
            return Width + 55;
        }else {
            if (indexPath.section == 0) {
                return 55;
            }else {
                return 44;
            }
        }
    }else {
        return 0;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 1) {
        if (indexPath.row == 1) {
            [UIView animateWithDuration:0.5 animations:^{
                self.sc.frame = CGRectMake(0, 0, Width, Height - 114);
                self.topTableVIew.hidden = YES;
                self.exchangeBtn.transform = CGAffineTransformMakeTranslation(Width / 2.0 - self.exchangeBtn.frame.size.width / 2 - 10, 0);
                self.exchangeLb.hidden = NO;
                self.priceLb.hidden = NO;
                
                self.goldLb.hidden = NO;
                self.baoyouLb.hidden = NO;
            }];
        }
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if (section == 0) {
        return 0;
    }else {
        return 20;
    }
}

/** 点击立即兑换*/
- (IBAction)clickExchangeBtn:(id)sender {
    SubmitDetialTableViewController *vc = [SubmitDetialTableViewController CreatSubmitDetialTableViewController];
    [self creatNav:vc];
    
}


//创建模态导航控制器
-(void)creatNav:(UIViewController *)view{
    
    UINavigationController *nav=[[UINavigationController alloc] initWithRootViewController:view];
    nav.navigationBar.barTintColor = [UIColor colorWithRed:254/255.0 green:154/255.0 blue:37/255.0 alpha:1];
    view.navigationItem.leftBarButtonItem=[[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"icon_back"] style:UIBarButtonItemStylePlain target:self action:@selector(dismiss)];
    [self presentViewController:nav animated:YES completion:nil];
}

- (void)dismiss {
    [self dismissViewControllerAnimated:YES completion:nil];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
